import { CloudSyncService } from './../service/cloudSyncService';
import { OrderService } from './../service/orderService';
import { ExpeditionOrderItem } from './../domain/model/expeditionOrder';
import { KitchenOrder } from './../domain/model/kitchenOrder';
import { KitchenOrderService } from './../service/kitchenOrderService';
import { KitchensolutionService } from './../service/kitchensolutionService';
import { ExpeditionOrderService } from './../service/expeditionOrderService';
import { Response, ServiceConfig, route, Guid, uniqueArray, intersectionArray } from '../common';
import { ExpeditionOrder } from '../domain/model';
import { WebException } from './webException';
import * as lodash from 'lodash';
import assert = require("assert");
import * as Koa from "koa";
import * as R from 'ramda';
import { DeliveryOrderService } from "../service/deliveryOrderService";

export class ExpeditionOrderController {
    private expeditionOrderService: ExpeditionOrderService;
    private deliveryOrderService: DeliveryOrderService;
    private kitchensOrderService: KitchenOrderService;
    private orderService: OrderService;
    private syncSvr: CloudSyncService;
    private origin = 999;
    constructor() {
        this.expeditionOrderService = ServiceConfig.Current.GetService<ExpeditionOrderService>("expeditionOrderService");
        this.deliveryOrderService = ServiceConfig.Current.GetService<DeliveryOrderService>("deliveryOrderService");
        this.kitchensOrderService = ServiceConfig.Current.GetService<KitchenOrderService>("kitchenOrderService");
        this.orderService = ServiceConfig.Current.GetService<OrderService>("orderService");
        this.syncSvr = ServiceConfig.Current.GetService<CloudSyncService>("cloudSyncService");
    }

    toString() {
        return "ExpeditionOrderController";
    }

    // 查询出品单
    @route({ method: "get", path: "/api/expeditionOrders" })
    async queryExpeditionOrder(ctx: Koa.Context, next) {
        const query = ctx.request.query;
        const paramsWhite = ["sourceTerminalIds", "status", "limit", "sortby", "order", "start", "end", "keyWord"];
        for (let key in query) {
            if (paramsWhite.indexOf(key) == -1) {
                throw new WebException(key + "参数不合法");
            }
        }
        if (query.sourceTerminalIds && !Array.isArray(query.sourceTerminalIds)) query.sourceTerminalIds = [query.sourceTerminalIds]
        query.limit && (query.limit = Number(query.limit))
        query.start && (query.start = Number(query.start))
        query.end && (query.end = Number(query.end))
        if (query.status && !Array.isArray(query.status)) query.status = [query.status]
        let retOrders = await this.expeditionOrderService.queryExpeditionOrder(query);
        let deliveryOrders = await this.deliveryOrderService.GetDeliveryOrders({
            start: query.start
        });
        let data = [];
        for (let i = 0; i < retOrders.length; i++) {
            let o: any = retOrders[i];
            if (o.status == 'delivered') {
                let deliverer = lodash.find(deliveryOrders, (item) => {
                    if (item.expediteOrderIds.indexOf(o.id) >= 0) {
                        return item.deliveryer;
                    }
                });
                if (deliverer) {
                    o.deliveryer = deliverer.deliveryer;
                }
            };
            data.push(o);
        }
        ctx.response.body = Response.ok("订单查询成功", data);;
        await next();
    }

    // 创建出品单
    @route({ method: "post", path: "/api/expeditionOrders" })
    async CreateExpeditionOrder(ctx: Koa.Context, next) {
        const expeditionOrder: ExpeditionOrder = ctx.request.body.order;

        const groupBykitchenOrderId = R.groupBy((expeditionOrderItem: ExpeditionOrderItem) => {
            return expeditionOrderItem.kitchenOrderId;
        })
        const result = groupBykitchenOrderId(expeditionOrder.items);
        const KitchenOrders = await Promise.all(Object.keys(result).map(kitchenOrderId => {
            //todo 应该先完成，在出品
            return this.kitchensOrderService.expediteOrderByItemIds(
                kitchenOrderId,
                result[kitchenOrderId].map(
                    expeditionOrderItem => expeditionOrderItem.kitchenOrderItemId
                )
            )
        }))
        const createdexpeditionOrder = await this.expeditionOrderService
            .CreateExpeditionOrder(expeditionOrder);
        const nextSerialNO = await this.generateExpeditionOrderSerialNO();
        ctx.response.body = Response.ok("创建出品单成功", {
            currentOrder: createdexpeditionOrder, KitchenOrders, nextSerialNO
        });

        await next();
    }

    // 获取出品单序列号
    @route({ method: "get", path: "/api/expeditionOrders/serialNO" })
    async getExpeditionOrderSerialNO(ctx: Koa.Context, next) {
        const serialNO = await this.generateExpeditionOrderSerialNO()
        ctx.response.body = Response.ok("获取出品单序列号", {
            serialNO
        });
        await next();
    }


    //取消出品出品单
    @route({ method: "post", path: "/api/expeditionOrders/:id/cancel" })
    async cancelExpeditionOrder(ctx: Koa.Context, next) {
        const storeId = ctx.accept.headers["storeid"];
        const terminal = ctx.request.body.terminal;
        const user = ctx.request.body.user;

        const expeditionOrderId: string = ctx.params.id;

        const resExpeditionOrder = await this.expeditionOrderService
            .deleteExpeditionOrderById(expeditionOrderId);
        const groupBykitchenOrderId = R.groupBy((expeditionOrderItem: ExpeditionOrderItem) => {
            return expeditionOrderItem.kitchenOrderId;
        })
        const result = groupBykitchenOrderId(resExpeditionOrder.items);
        const KitchenOrders = await Promise.all(Object.keys(result).map(kitchenOrderId => {
            //todo 应该先完成，在出品
            let itemIds = result[kitchenOrderId].map(expeditionOrderItem => expeditionOrderItem.kitchenOrderItemId);
            return this.kitchensOrderService.cancelExpediteOrderByItemIds(kitchenOrderId, itemIds)
        }))
        ctx.response.body = Response.ok("取消出品单成功", {
            currentOrder: resExpeditionOrder, KitchenOrders
        });

        this.syncExpeditionOrders(resExpeditionOrder, storeId, terminal, user);
        await next();
    }

    async generateExpeditionOrderSerialNO() {
        const serialNO = await this.orderService.SerialNoMaker(this.origin);
        return serialNO.replace(this.origin.toString() + "-", "");
    }

    syncExpeditionOrders(expeditionOrder: any, storeId, terminal, user) {
        //删除不要数据
        delete expeditionOrder.createTime
        delete expeditionOrder.extend
        // delete expeditionOrder.deliveryerId
        // delete expeditionOrder.deliveryBeginTimeStringFormat
        // delete expeditionOrder.deliveryFinishTimeStringFormat
        delete expeditionOrder.beginTimeStringFormat
        delete expeditionOrder.finishTimeStringFormat
        this.syncSvr.DomainDataSyncPackage(
            [
                {
                    id: expeditionOrder.id,
                    body: expeditionOrder,
                    entityName: "expeditions"
                }
            ]
            , {
                storeId,
                terminal,
                user
            }
        );
    }
}